/**
 * Automatic Subtitle Downloader
 * http://code.google.com/p/autosubdown/
 * 
 * Copyright 2010-2011 Raphael Medeiros.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */
package com.byraphaelmedeiros.autosubdown;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;

import com.byraphaelmedeiros.aboutbox.AboutBox;
import com.byraphaelmedeiros.autosubdown.domain.Config;
import com.byraphaelmedeiros.autosubdown.domain.Provider;
import com.byraphaelmedeiros.autosubdown.domain.ProviderType;
import com.byraphaelmedeiros.autosubdown.domain.Rule;
import com.byraphaelmedeiros.byrmutils.FileUtils;




/**
 * Main class
 * 
 * @author Raphael Medeiros
 *
 */
public class Main {
	
	private static final String VERSION = "1.0";
	
	private static final String STOP_SERVICE = "Stop Service";
	private static final String START_SERVICE = "Start Service";

	private static final String DOWNLOAD = "download";
	private static final String DAEMON = "daemon";
	private static final String ADD = "add";
	private static final String ADD_RULE = "rule";
	private static final String HELP = "help";
	private static final String DAEMON_START = "start";
	private static final String DAEMON_STOP = "stop";
	
	private static final String PATH_PREFIX = "/com/byraphaelmedeiros/autosubdown/resources/";
	
	private static final AboutBox aboutBox = new AboutBox("AutoSubDown", "1.0", "2011", FileUtils.getContent(Main.class.getResourceAsStream(PATH_PREFIX + "license.txt")), PATH_PREFIX + "AutoSubDownAbout.jpg");

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//configSample();
		if (args == null || args.length <= 0) {
			executeInTray();
			
		} else {
			String argZero = args[0];
			
			if (DOWNLOAD.equalsIgnoreCase(argZero)) {
				AutoSubDown.download();
				
			} else if (DAEMON.equalsIgnoreCase(argZero)) {
				String argOne = args[1];
				
				if (DAEMON_START.equalsIgnoreCase(argOne)) {
					AutoSubDown.deamon(true);
					
				} else if (DAEMON_STOP.equalsIgnoreCase(argOne)) {
					AutoSubDown.deamon(false);
					
				} else {
					System.out.println("Invalid option!");
					System.out.println();
					showHelp();
				}
				
			} else if (HELP.equalsIgnoreCase(argZero)) {
				showHelp();
				 
			} else if (ADD.equalsIgnoreCase(argZero)) {
				String argOne = args[1];
				
				if (ADD_RULE.equalsIgnoreCase(argOne)) {
					String argTwo = args[2];
					
					if (argTwo == null || "".equals(argTwo.trim())) {
						System.out.println("Invalid rule data!");
						System.out.println();
						System.out.println("Sintaxe: ID;NAME;SEARCH_FOR;NOT_INCLUDE;EPISODE;DOWNLOAD_TO");
						System.out.println("Sample.: 1;Fringe;fringe;720;1-2,1-25;C:\\series\\fringe\\");
						
					} else {
						String[] ruleData = argTwo.split(";");
						
						long id = Long.parseLong(ruleData[0]);
						String name = ruleData[1];
						String searchFor = ruleData[2];
						String notInclude = ruleData[3];
						String episode = ruleData[4];
						String downloadTo = ruleData[5];
						
						Rule rule = new Rule(id, name, searchFor, notInclude, episode, downloadTo);
						Config.getInstance().addRule(rule);
					}
				}
			}
		}
	}

	/**
	 * 
	 */
	private static void executeInTray() {
		// Check the SystemTray is supported
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        
        final PopupMenu popup = new PopupMenu();
        
        final TrayIcon trayIcon = new TrayIcon(createImage(PATH_PREFIX + "AutoSubDownIcon.gif", "AutoSubDown"));
        
        final SystemTray tray = SystemTray.getSystemTray();
        
        
        MenuItem downloadItem = new MenuItem("Download");
        MenuItem deamonItem = new MenuItem(START_SERVICE);
        MenuItem aboutItem = new MenuItem("About");
        
        MenuItem exitItem = new MenuItem("Exit");
        
        popup.add(downloadItem);
        popup.add(deamonItem);
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(exitItem);
        
        trayIcon.setPopupMenu(popup);
        
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }
        
        exitItem.addActionListener(new ActionListener() {
        	@Override
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
        
        downloadItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				AutoSubDown.download();
			}
		});
        
        aboutItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (!aboutBox.isVisible()) {
		            aboutBox.setVisible(true);
		            aboutBox.requestFocus();
		        } else {
		            aboutBox.setVisible(false);
		        }
			}
		});
        
        deamonItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				MenuItem serviceItem = (MenuItem) evt.getSource();
				
				if (START_SERVICE.equalsIgnoreCase(serviceItem.getLabel())) {
					AutoSubDown.deamon(true);
					
					popup.getItem(0).setEnabled(false);
					
					serviceItem.setLabel(STOP_SERVICE);
				} else {
					AutoSubDown.deamon(false);
					
					popup.getItem(0).setEnabled(true);
					
					serviceItem.setLabel(START_SERVICE);
				}
			}
		});
	}
	
	// Obtain the image URL
    private static Image createImage(String path, String description) {
        URL imageURL = Main.class.getResource(path);
        
        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }

	private static void configSample() {
		Config config = Config.getInstance();
		
		config.setWait(30000);
		config.setExtract(true);
		
		List<Provider> providers = new ArrayList<Provider>();
		providers.add(new Provider(1, "insubs", "http://www.insubs.com/rss/index.php", ProviderType.RSS));
		//providers.add(new Provider(2, "subsfreak", "http://twitter.com/subsfreak"));
		
		config.setProviders(providers);
		
		List<Rule> rules = new ArrayList<Rule>();
		rules.add(new Rule(1, "The Event", "the.event", "720", "1-2,1-25", "C:\\Users\\raphael\\Desktop\\"));
		//rules.add(new Rule(2, "Fringe", "fringe", "720", "1-2,1-25", "C:\\Users\\raphael\\Desktop\\"));
		
		config.setRules(rules);
		
		config.save();
	}

	private static void showHelp() {
		System.out.println("AutoSubDown " + VERSION);
		System.out.println("by Raphael Medeiros");
		System.out.println();
		
	}
}